<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantCode"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in plants"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="到货日期">
          <el-date-picker
            v-model="searchParam.arriveTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getarriveDate"
          />
        </el-form-item>
        <el-form-item label="存储地点">
          <el-select
            v-model="searchParam.inboundStorageLocationName"
            clearable
            placeholder="请选择存储地点"
          >
            <el-option
              v-for="item in storageLocations"
              :key="item.id"
              :label="item.storageLocationName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          :disabled="ids.length === 0"
          @click="sends(ids)"
          >确认发货</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column
          label="工厂号"
          prop="inboundPlantCode"
          min-width="70"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="工厂名称"
          prop="inboundPlantName"
          min-width="120"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="送货单号"
          prop="deliveryCode"
          min-width="160"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="到货日期"
          prop="arriveTime"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
          :formatter="formatDate"
        />

        <el-table-column
          label="要货地点"
          prop="inboundStorageLocationName"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="150"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          label="打印时间"
          prop="printTime"
          min-width="150"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          label="发货时间"
          prop="sendTime"
          min-width="150"
          show-overflow-tooltip
          header-align="center"
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserId"
          min-width="70"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          label="发货状态"
          prop="isSend"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <el-tag>
              <span v-show="scope.row.isSend == '0'">未发货</span>
              <span v-show="scope.row.isSend == '1'">已发货</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="260"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.isSend === 1"
              @click="toggleIsSend(scope.row)"
            >
              确认发货
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看发货清单
            </el-button>

            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <wmsdeliverys-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "SRMWMSDELIVERY",
  inheritAttrs: false,
});
let plants = ref([]);
let storageLocations = ref([]);
// 请求参数
const requestApi = "/srm/core/wmsdelivery/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  inboundPlantName: "",
  inboundStorageLocationName: "",
  arriveTimeSearch: [],
  arriveDateStart: "",
  arriveDateEnd: "",
};

const deleteParam = {
  api: "/srm/core/wmsdelivery/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlants();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
async function toggleIsSend(row: any) {
  // 弹出确认提示框
  ElMessageBox.confirm(`确定要发货此记录吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true; // 显示加载状态
      request({
        url: `/srm/core/wmsdelivery/send`,
        method: "post",
        data: row,
      })
        .then((res) => {
          ElMessage.success(`发货成功`);
          getTableList();
        })
        .catch((res) => {
          return;
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 用户取消操作
      console.log("用户取消操作");
      getTableList();
    });
}
// 查询详情
async function getInfo(id: string) {
  request({
    url: `/srm/core/wmsdelivery/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
async function getPlants() {
  const data = await request({
    url: "/srm/core/common/getPlantList",
    method: "get",
  });
  plants.value = data.data;
}
async function getStorageLocations() {
  const data = await request({
    url: "/srm/core/storagelocation/getLists",
    method: "get",
  });
  storageLocations.value = data.data;
}

/** 打开交货单表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改交货单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增交货单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开交货单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "交货单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function redirectToOtherPage(this: any) {
  // 使用 $router.push() 导航到目标路径
  this.$router.push("/srm/partner/srmdeliverynote/index");
}

function sends(ids: { value: any }) {
  // 弹出确认提示框
  ElMessageBox.confirm(`确定要发货此记录吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 用户点击确认后执行的操作
      request({
        url: "/srm/core/wmsdelivery/sends",
        method: "post",
        data: ids, // 直接发送ID数组
      })
        .then(() => {
          // 发货成功后的操作
          reset();
          ElMessage.success("发货成功");
        })
        .catch(() => {
          // 发货失败后的操作
          ElMessage.error("发货失败");
        });
    })
    .catch(() => {
      // 用户点击取消后的操作，如果需要的话
      ElMessage.info("已取消发货");
    });
}
function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
function getarriveDate(data: any) {
  if (data) {
    searchParam.value.arriveDateStart = data[0];
    searchParam.value.arriveDateEnd = data[1];
  } else {
    searchParam.value.arriveDateStart = "";
    searchParam.value.arriveDateEnd = "";
  }
}
function formatDate(row, column, cellValue) {
  // 假设到货日期的格式为 'YYYY-MM-DD HH:mm:ss'
  // 截取年月日部分
  let datePart = cellValue.split(" ")[0]; // 获取日期部分，例如 'YYYY-MM-DD'
  return datePart;
}
</script>
